<?php

namespace App\Http\Controllers\Api\V1;
use App\Models\CouponRecord;
use App\Models\Coupon;
use Illuminate\Support\Facades\Cache;
use App\Services\TransferApple\TransferApple;
use App\Services\TransferApple\TransferAppleRequest;
use App\Services\ExchangeBalance\ExchangeBalance;
use App\Services\ExchangeBalance\ExchangeBalanceRequest;
use App\Http\Controllers\Api\V1\Queries\AppleQuery;
use Brick\Math\RoundingMode;
use App\Http\Controllers\Api\V1\Resources\CouponRecordsResource;
use App\Services\MakeCouponsUsePoints\TakeCouponsRequest;
use App\Services\MakeCouponsUsePoints\MakeCouponsUseArivity;
use Carbon\Carbon;
use App\Supports\Qrcode\WapQrcode;
use GuzzleHttp\Client;

class CouponController extends Controller
{
	
	public function couponMerchantRecords()
	{ 
		$merchant = request()->user();
		
		$couponRecords  = $merchant->couponRecords()->orderByDesc('id')->paginate();

		return CouponRecordsResource::collection($couponRecords);
	}

	public function takeCoupon()
	{
		$lock = Cache::lock('point_to_coupons', 15);

        try {

            if (! $lock->get()) fail('高峰拥挤，请再试');

            $request = app(TakeCouponsRequest::class);
            

            $record = app(MakeCouponsUseArivity::class, [
                'user' => $request->user(),
                'coupon_id' => $request->coupon_id,
                'activity_id' => $request->activity_id,
            ])->make();

           return response()->json(['record' => $record->toArray()]);

        } finally {
            $lock->release();
        }

	}

	public function use()
	{ 
		$merchant = request()->user();
		
		$userId = request("user_id");
		$code = request("code","");

		//$coupon =Coupon::query()->where("code",$code)->first();
		


		$record = CouponRecord::query()->where("user_id",$userId)->where("code",$code)->first();

		if(!$record){
			fail("该优惠卷不存在!");
		}

		if($record->status =="used"){

			fail("优惠卷已被使用!");
		}

		if(strtotime($record->expired_at)<time() ){

			fail("优惠卷已过期!");
		}

		if($record->coupon->scope == "shop"){
			
			 $merchants = str_replace("[","",$record->coupon->merchant_ids);
	        $merchants = str_replace("]","",$merchants);
	        $merchants = str_replace('"',"",$merchants);

	        if(!in_array($merchant->id,$merchants)){
	        	fail("该商户无法核销该优惠卷!");

	        }
		}

		$record->update(['used_at'=>Carbon::now(),"status"=>"used",'merchant_id'=>$merchant->id]);

		return new CouponRecordsResource($record);
	}


	public function records()
	{ 
		$user = request()->user();
		
		$query = $user->couponRecords();

		if(request('used')==1){

			$query = $query->where("status","unused")->where("expired_at",'>=',date("Y-m-d H:i:s",time()));
		}elseif(request('used')==2){
			
			$query = $query->where("status","used");
		}elseif(request('used')==3){
			$query = $query->where("status","unused")->where("expired_at",'<',date("Y-m-d H:i:s",time()));
		}


		$couponRecords = $query->orderByDesc('id')->paginate();

		return CouponRecordsResource::collection($couponRecords);
	}


	public function getDeliyunSign($startTime,$endTime){


		$dataArr = [
			'shopId'=>'34604',
			'beginDate'=>$startTime,
			'endDate'=>$endTime,
			'saleType'=>'2',
			'saleValue'=>'180'
		];

		$dataJson =json_encode($dataArr);

		$commonData = [
			'accessKeyID'=>env("DELIYUN_APP_ID"),
			'commKey'=>env('DELIYUN_COMMKEY'),
			'version'=>'3.0',
			'timestamp'=>time(),
			'data'=>urlencode($dataJson)
		];




		$sign= $this->generateSign($commonData, env('DELIYUN_APP_SECRET'));

		$commonData['sign'] = $sign;

		$url = "https://openapi.deliyun.cn/parking/releaseCoupons";

		$client = new Client(['Content-Type' => 'application/x-www-form-urlencoded']);


		$response = $client->post($url,  ['query' => $commonData])->getBody()->getContents();

		$response = json_decode($response,true);
		if($response['data']){
			return $response['data'];
		}



	}

	public function generateSign($params,$secret)
    {
        

        // 按ASCII码升序排序
        ksort($params);
        // 拼接键值对
        $queryString = urldecode(http_build_query($params));


        // 追加密钥
        $signString = $queryString ."&accessKeySecret=".$secret;

        //$signString=urlencode($signString);

        //dd(strtolower(md5($signString)));
        // 生成小写MD5签名
        return strtolower(md5($signString));


    }

    public function parkRecord()
    {

    	$user = request()->user();
    	$record = CouponRecord::find(request('id'));
    	if($record->coupon->type =="park"){

    		if(empty($record->qrcode) && $record->status=="unused"){
    			

				if($record->coupon->is_date == 0){
					$startTime = date("Y-m-d",time())." ".$record->coupon->no_date_started_at;
					$endTime = date("Y-m-d",time())." ".$record->coupon->no_date_end_at;

					$startTime = strtotime($startTime);
					$endTime = strtotime($endTime);


				}else{
					$startTime = strtotime($record->coupon->start_time);
					$endTime = strtotime($record->coupon->end_time);

				}

				$res = $this->getDeliyunSign($startTime,$endTime);

				$url = $res['url'];
				$record->update(['qrcode_url'=>$res['url'],'qrcode'=>$res['number']]);
    		}else{

    			$url = $record->qrcode_url;
    		}

    		return response()->json([
		        'url'=>$url
	        ]);
    	}
    }

	public function record()
	{
		$user = request()->user();

		$record = CouponRecord::find(request('id'));

		if($record->coupon->type =="park"){

			$startTime = strtotime($record->coupon->start_time);
			$endTime = strtotime($record->coupon->end_time);

			$res = $this->getDeliyunSign($startTime,$endTime);
			//dd($res);
			// $qrcodeMaker = new WapQrcode($user, $record);

			 $qrcode = $res;
		
			
			

		}else{

			$qrcodeMaker = new WapQrcode($user, $record);

			//https://wx.deliyun.cn/sale/qrcode?punitId=21923&iden=gseT8h2GOLExQeWLTuI
			$qrcode = $qrcodeMaker->make($user->id."+".$record->code);
		}
		

		$destory_at = "00:00:00";
    	if($record->status =="unused"){

    		if(strtotime((string)$record->expired_at) > time()){
    			$destory_at= strtotime((string)$record->expired_at)- time();
    			$destory_at = date('H:i:s', $destory_at);
    		}
    	}

        return response()->json([
        	'id' => (int)$record->id,
	        'code' => $record->code,
	        'coupon' => $record->coupon,
	        'status' => (string)$record->status,
	        'used_at' => (string)$record->used_at,
	        'destory_at'=>$destory_at,
	        'hour'=>substr($destory_at, 0, 2),
	        'minute'=>substr($destory_at, 3, 2),
	        'second'=>substr($destory_at, 6, 2),
	        'created_at' => (string)$record->created_at,
	        'qrcode'=>$qrcode
        ]);
		

	}


	public function allRecords()
	{ 
		
		$couponRecords = CouponRecord::query()->orderByDesc('id')->take(15)->get();

		return CouponRecordsResource::collection($couponRecords);
	}

	
}
